import http from 'http';
import express from 'express';
import { Server } from 'socket.io'
const app = express();
const server = http.createServer(app);

app.get('/', () => {
    console.log('hello');
})

const io = new Server(server, {
    cors: {
        origin: '*'
    }
});

/**
 * @description socket.io 监听客户端连接
 * @method emit 对当前的client发送消息
 * @method broadcast.emit 对socket中其他用户发送消息，除了自己
 */
const socketList = {}
const userList = []
io.on('connection', (socket) => {
    console.log(socket.handshake.query.userName + ' 连接成功...')
    /**
     * 新用户连接成功后广播通知所以用户包括自己
     */
    const { userName, userId } = socket.handshake.query;
    const userInfo = {
        userName,
        userId,
    }
    console.log(userInfo);
    userList.push(userInfo)
    socketList[userId] = socket
    socket.emit('add-user', userList);
    socket.broadcast.emit('add-user', userList);

    /**
     * 转发消息到指定用户
     */
    socket.on('sendToUser', (message) => {
        socketList[message.userId].emit('message', {
            type: 'user',
            message
        });
    })

    /**
     * 监听统一个消息
     */
    socket.on('message', (message) => {
        console.log('收到消息', message)
        socket.broadcast.emit('message', message);
    })

    /**
     * 监听呼叫
     */
    socket.on('call', (data) => {
        socket.broadcast.emit('call', data);
    })

    /**
    * 监听关闭
    */
    socket.on('stop-call', () => {
        socket.broadcast.emit('stop-call');
    })

    /**
     * 将收到的offer广播给其他用户
     */
    socket.on('offer', (data) => {
        console.log('转发offer')
        socket.broadcast.emit('offer', data);
    });

    /**
     * 将收到的answer广播给其他用户
     */
    socket.on('answer', (data) => {
        console.log('转发answer', data)
        socket.broadcast.emit('answer', data);
    });

    /**
     * 将收到的ICE candidate广播给其他用户
     */
    socket.on('ice-candidate', (data) => {
        console.log('转发acandidate')
        socket.broadcast.emit('ice-candidate', data);
    });

    /**
     * 用户断开连接时的处理
     */
    socket.on('disconnect', () => {
        const user = userList.find(userInfo => userInfo.userId === userId)
        const index = userList.findIndex(userInfo => userInfo.userId === userId)
        userList.splice(index, 1)
        socket.broadcast.emit('add-user', userList);
        delete socketList[userId]
        console.log(user.userName + ' 断开连接...');
        console.log(user)
    });
});



server.listen(8090, () => {
    console.log("server is up and running on port 8090");
});
